package logic

import (
	"akeju/model/redis"
	"context"
	"fmt"
	"math/rand"
	"time"

	"akeju/userrpc/internal/svc"
	"akeju/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("sendSmsFive" + in.Account)
	if get.Val() >= "1" {
		return nil, fmt.Errorf("5分钟内只能发送一次，请5分钟后再试")
	}

	cmd, _ := redis.Rdb.Get("sendSmsHour" + in.Account).Int64()
	if cmd >= 10 {
		return nil, fmt.Errorf("2小时内只能发送10次，请两小时后在试")
	}
	code := rand.Intn(9000) + 1000
	//sms, err := pkg.SendSms(in.Account, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	redis.Rdb.Set("sendSms"+in.Source+in.Account, code, time.Minute*3)

	redis.Rdb.Set("sendSmsFive"+in.Account, 1, time.Minute*5)

	incr := redis.Rdb.Incr("sendSmsHour" + in.Account)
	if incr.Val() == 1 {
		redis.Rdb.Expire("sendSmsHour"+in.Account, time.Hour*2)
	}
	return &userrpc.SendSmsResponse{}, nil
}
